<template>
  <div class="detail-wrapper">
    <div class="top">
      <el-form
        class="data-form"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="110px"
      >
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="是否产生费用" prop="needPay">
              <el-radio-group
                v-model="form.needPay"
                @change="handleChangeSFCSFY"
              >
                <el-radio
                  v-for="(item, index) of dict['yn']"
                  :key="index"
                  :label="item.value"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="part" v-for="(item, index) of form.list" :key="index">
          <div class="part-top">
            <div class="part-top-item">
              <span class="part-top-item-label">所属园区：</span>
              <span class="part-top-item-value">{{
                detail[index].parkName
              }}</span>
            </div>
            <div class="part-top-item">
              <span class="part-top-item-label">检查场景：</span>
              <span class="part-top-item-value">{{
                detail[index].senceName
              }}</span>
            </div>
            <div class="part-top-item">
              <span class="part-top-item-label">检查点：</span>
              <span class="part-top-item-value">{{
                detail[index].pointName
              }}</span>
            </div>
            <div class="part-top-item">
              <span class="part-top-item-label">隐患图片：</span>
              <span class="part-top-item-value">
                <el-image
                  class="img"
                  fit="cover"
                  :preview-src-list="[detail[index].dangerImgFile.fileUrl]"
                  preview-teleported
                  :src="detail[index].dangerImgFile.fileUrl"
                />
              </span>
            </div>
            <div class="part-top-item">
              <span class="part-top-item-label">检查时间：</span>
              <span class="part-top-item-value">{{
                detail[index].createTime
              }}</span>
            </div>
          </div>
          <div class="part-form">
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item
                  label="隐患描述"
                  :prop="'list.' + index + '.repairDesc'"
                  :rules="rules.repairDesc"
                >
                  <el-input
                    class="data-input"
                    v-model="item.repairDesc"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="整改措施"
                  :prop="'list.' + index + '.repairMethod'"
                  :rules="rules.repairMethod"
                >
                  <el-input
                    class="data-input"
                    v-model="item.repairMethod"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="整改对象"
                  :prop="'list.' + index + '.repairCompany'"
                  :rules="rules.repairCompany"
                >
                  <el-select
                    class="search-select"
                    v-model="item.repairCompany"
                    placeholder="请选择"
                    :disabled="index !== 0"
                    @change="handleChangeZGDX"
                  >
                    <el-option
                      v-for="(item, index) of dict[
                        'special_task_publish_scope'
                      ]"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="整改部门"
                  :prop="'list.' + index + '.repairDept'"
                  :rules="rules.repairDept"
                  v-if="item.repairCompany === '1'"
                >
                  <el-select
                    class="search-select"
                    v-model="item.repairDept"
                    placeholder="请选择"
                    @change="initDepartmentPersonOptions"
                  >
                    <el-option
                      v-for="(item, index) of departmentOptions"
                      :key="index"
                      :label="item.name"
                      :value="item.pkid"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  label="整改部门"
                  :prop="'list.' + index + '.repairDept'"
                  :rules="rules.repairDept"
                  v-else
                >
                  <el-select
                    class="search-select"
                    v-model="item.repairDept"
                    placeholder="请选择"
                    @change="initTenantPersonOptions"
                  >
                    <el-option
                      v-for="(item, index) of tenantOptions"
                      :key="index"
                      :label="item.name"
                      :value="item.pkid"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="责任人"
                  :prop="'list.' + index + '.dutyPerson'"
                  :rules="rules.dutyPerson"
                >
                  <el-select
                    class="search-select"
                    v-model="item.dutyPerson"
                    placeholder="请选择"
                    v-if="item.repairCompany === '1'"
                  >
                    <el-option
                      v-for="(item, index) of departmentPerosnOptions[
                        item.repairDept
                      ]"
                      :key="index"
                      :label="item.userName"
                      :value="item.pkid"
                    />
                  </el-select>
                  <el-select
                    class="search-select"
                    v-model="item.dutyPerson"
                    :prop="'list.' + index + '.dutyPerson'"
                    :rules="rules.dutyPerson"
                    placeholder="请选择"
                    v-else
                  >
                    <el-option
                      v-for="(item, index) of tenantPersonOptions[
                        item.repairDept
                      ]"
                      :key="index"
                      :label="item.userName"
                      :value="item.pkid"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  label="整改期限"
                  :prop="'list.' + index + '.deadLine'"
                  :rules="rules.deadLine"
                >
                  <el-date-picker
                    class="data-input"
                    v-model="item.deadLine"
                    type="date"
                    placeholder="请选择"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8" v-if="form.needPay === '1'">
                <el-form-item
                  label="费用(元)"
                  :prop="'list.' + index + '.cost'"
                  :rules="rules.cost"
                >
                  <el-input
                    class="data-input"
                    v-model="item.cost"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item
                  v-if="item.repairCompany === '2'"
                  label="是否实地巡查"
                  :prop="'list.' + index + '.patrol'"
                  :rules="rules.patrol"
                >
                  <el-radio-group v-model="item.patrol">
                    <el-radio
                      v-for="(i, iIndex) of dict['yn']"
                      :key="iIndex"
                      :label="i.value"
                      >{{ i.name }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-form>
    </div>

    <div class="bottom">
      <el-button @click="handleClose(false)" :loading="loading">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading"
        >确定</el-button
      >
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useDict } from '@/hooks/useDict'
import {
  getDepartmentList,
  getUserList,
} from '@/api/manager/systemManage/user.js'
import { tenantPageList } from '@/api/manager/dataManage/tenant.js'
import {
  dangerApply,
  getDangerList,
} from '@/api/manager/inspectionManage/rectificationManage.js'
import { useRoute, useRouter } from 'vue-router'

const { dict, getDictValue } = useDict(['yn', 'special_task_publish_scope'])
const router = useRouter()
const route = useRoute()

defineOptions({
  name: 'AddDialog',
})
const formRef = ref(null)
const form = ref({
  needPay: '1',
  list: [],
})
const emit = defineEmits(['close'])
const title = ref('')
const dialogVisible = ref(false)
const handleClose = (isFlash) => {
  router.push({ name: 'rectificationManage' })
}

const rules = ref({
  needPay: [{ required: true, message: '请选择是否产生费用', trigger: 'blur' }],
  repairDesc: [{ required: true, message: '请输入隐患描述', trigger: 'blur' }],
  repairMethod: [
    { required: true, message: '请输入整改措施', trigger: 'blur' },
  ],
  repairCompany: [
    { required: true, message: '请选择整改对象', trigger: 'blur' },
  ],
  repairDept: [{ required: true, message: '请选择整改部门', trigger: 'blur' }],
  dutyPerson: [{ required: true, message: '请选择责任人', trigger: 'blur' }],
  deadLine: [{ required: true, message: '请选择整改期限', trigger: 'blur' }],
  cost: [{ required: true, message: '请选择输入费用', trigger: 'blur' }],
  patrol: [{ required: true, message: '请选择是否实地巡查', trigger: 'blur' }],
})

const loading = ref(false)
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      let params = []
      form.value.list.forEach((item) => {
        params.push({
          ...item,
          needPay: form.value.needPay,
        })
      })
      loading.value = true
      try {
        let res = await dangerApply(params)
        if (res.success) {
          ElMessage.success('整改申请成功')
          handleClose()
        } else {
          ElMessage.error(res.message)
        }
        loading.value = false
      } catch (error) {
        loading.value = false
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}
const detail = ref([])
const handleDetail = async () => {
  const res = await getDangerList({
    pageIndex: 1,
    pageSize: 9999,
    dangerIds: route.query.pkid,
  })
  let list = []
  res.data.list.forEach((item) => {
    list.push({
      dangerId: item.pkid,
      repairDesc: item.appDesc,
      patrol: '1',
    })
  })
  detail.value = res.data.list
  form.value.list = list
}

// 资产公司部门、承租方单位
const departmentOptions = ref([])
const tenantOptions = ref([])
const initDepartmentOptions = async () => {
  const res = await getDepartmentList({ unitId: '10501' })
  if (!res.success) {
    ElMessage.error(res.message)
    return
  }
  departmentOptions.value = res.data
}
const initTenantOptions = async () => {
  const res = await tenantPageList({ pageIndex: 1, pageSize: 9999 })
  tenantOptions.value = res.data.list
}
// 资产公司人员、承租方人员
const departmentPerosnOptions = ref({})
const tenantPersonOptions = ref({})
const initDepartmentPersonOptions = async (val) => {
  if (
    departmentPerosnOptions.value[val] &&
    departmentPerosnOptions.value[val].length > 0
  ) {
    return
  }
  const res = await getUserList({
    pageIndex: 1,
    pageSize: 9999,
    unitId: '10501',
    deptId: val,
    userStatus: 1,
    type: ['1'],
  })
  departmentPerosnOptions.value[val] = res.data.list
}
const initTenantPersonOptions = async (val) => {
  if (
    tenantPersonOptions.value[val] &&
    tenantPersonOptions.value[val].length > 0
  ) {
    return
  }
  const res = await getUserList({
    pageIndex: 1,
    pageSize: 9999,
    type: ['2'],
    unitContent: val,
    userStatus: 1,
  })
  tenantPersonOptions.value[val] = res.data.list
}

// 修改是否产生费用
const handleChangeSFCSFY = () => {
  form.value.list.forEach((item) => {
    item.cost = ''
  })
}
// 修改整改对象
const handleChangeZGDX = (val) => {
  form.value.list.forEach((item) => {
    item.repairCompany = val
    item.repairDept = ''
    item.dutyPerson = ''
  })
}
onMounted(() => {
  initDepartmentOptions()
  initTenantOptions()
  if (route.query.pkid) {
    handleDetail()
  }
})
</script>
<style lang="scss" scoped>
.detail-wrapper {
  width: 100%;
  height: 100%;
  background: #ffffff;
  box-shadow: 0px 0px 10px 0px rgba(72, 121, 238, 0.1);
  box-sizing: border-box;
  padding-top: 20px;
  .top {
    width: 100%;
    height: calc(100% - 70px);
    box-sizing: border-box;
    padding: 0 20px 20px 20px;
    overflow-y: scroll;

    &::-webkit-scrollbar {
      display: none;
    }

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #151515;
      position: relative;
      padding-left: 10px;
      margin-bottom: 20px;
      display: flex;
      align-items: center;

      &::before {
        content: ' ';
        position: absolute;
        left: 0;
        top: 50%;
        width: 4px;
        height: 16px;
        background: linear-gradient(0deg, #4575ee 0%, #6297f5 100%);
        border-radius: 2px;
        transform: translateY(-50%);
      }
      .el-button {
        margin-left: 10px;
      }
    }
  }
  .bottom {
    width: 100%;
    height: 70px;
    box-sizing: border-box;
    border-top: 1px solid #d5deed;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.part {
  width: 100%;
  border: 1px solid #d5deed;
  border-radius: 4px;
  margin-bottom: 15px;
  &-top {
    width: 100%;
    height: 50px;
    box-sizing: border-box;
    padding: 0 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: aliceblue;
    &-item {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }
  }
  &-form {
    width: 100%;
    box-sizing: border-box;
    padding: 20px 40px 0 20px;
  }

  .img {
    width: 80px;
    height: 40px;
  }
}
</style>
